package smashedapples.twitter
{

	import com.adobe.serialization.json.JSON;

	import flash.events.TimerEvent;
	import flash.utils.Timer;

	import mx.collections.ArrayCollection;
	import mx.events.FlexEvent;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;

	import smashedapples.core.NonVisualComponent;
	import smashedapples.twitter.vo.TweetVO;
	import smashedapples.utils.ValueObjectUtils;

	[Event( name="result",type="mx.rpc.events.ResultEvent" )]
	[Event( name="fault",type="mx.rpc.events.FaultEvent" )]
	[Event( name="twitterTimeLineUpdated",type="AppEvent" )]

	public class TwitterPublicTimeLineApi extends NonVisualComponent
	{

		public function TwitterPublicTimeLineApi():void
		{
			this.addEventListener( FlexEvent.CREATION_COMPLETE, handleCreationComplete );
		}

		public var interval:Number = 6000;


		[Bindable( "twitterPublicTimeLineUpdated" )]
		public var result:ArrayCollection = new ArrayCollection();


		private var timer:Timer;

		protected function handleResult( event:ResultEvent ):void
		{
			var a:Array = JSON.decode( String( event.result )) as Array;
			var r:Array = ValueObjectUtils.typeArray( a, TweetVO )

			for each( var tweet:TweetVO in r )
			{
				this.result.addItem( tweet );
			}


			//this.result = new ArrayCollection( ValueObjectUtils.typeArray( a, TweetVO ));
			dispatchEvent( new AppEvent( "twitterPublicTimeLineUpdated" ));
		}

		private function handleCreationComplete( event:FlexEvent ):void
		{
			setUpPublicTimeLinePoll();
		}

		private function getPublicTimeLineImpl():void
		{
			var service:HTTPService = new HTTPService();
			service.url = TwitterURLs.PUBLIC_TIMELINE_URL;
			service.resultFormat = "text";
			service.showBusyCursor = true;
			service.addEventListener( ResultEvent.RESULT, handleResult );
			service.addEventListener( FaultEvent.FAULT, handleFault );
			service.send();
		}

		private function handleFault( event:FaultEvent ):void
		{
			trace( event.fault );
		}

		private function handleTimerCompleteEvent( event:TimerEvent ):void
		{
			trace( "handleTimerCompletEvent" );
			getPublicTimeLineImpl();
			this.setUpPublicTimeLinePoll();
		}

		private function setUpPublicTimeLinePoll():void
		{
			if( timer != null )
			{
				timer.stop();
				timer.reset();
			}
			else
			{
				timer = new Timer( interval, 1 );
				timer.addEventListener( TimerEvent.TIMER_COMPLETE, handleTimerCompleteEvent );
			}

			timer.start();
		}

	}
}